package com.macaupass.sdkDemo

import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.View.OnClickListener
import android.widget.*
import com.google.gson.Gson

import com.macau.pay.sdk.MacauPaySdk
import com.macau.pay.sdk.base.PayResult
import com.macau.pay.sdk.interfaces.MacauPaySdkInterfaces
import com.macau.pay.sdk.util.Logger

import java.io.IOException

import okhttp3.*
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*


@Deprecated("當前界面使用的是舊的sdk,建議使用新的sdk調用接口,包括調起支付的MPaySdk,以及回調接口:MPaySdkInterfaces")
class MainActivity : Activity(), OnClickListener, MacauPaySdkInterfaces {
    /**
     * 阿里支付的兩個預下單地址
     */
    private val alipay_url_uat = "http://202.86.151.170/macaupay_sdk3/MerchantNoAccPay"
    private val alipay_url_sit = "http://14.29.69.182:40001/macaupay_sdk3/MerchantNoAccPay"

    /**
     * MPay支付的兩個預下單地址
     */
    private val mpay_url_uat = "http://202.86.151.170/macaupay_sdk3/MerchantmerchantPayApp"
    private val mpay_url_sit = "http://14.29.69.182:40001/macaupay_sdk3/MerchantmerchantPayApp"

    private val wechatpay_url = "https://sitopenapi.macaupay.com.mo/mpay_demo/comn.json"

    private val respCreateMPayOrderSucceed = 1
    private val respCreateAliPayOrderSucceed = 2
    var rbSit: RadioButton? = null
    var rbUat: RadioButton? = null
    private var btnPayAli: LinearLayout? = null
    private var btnPayMacau: LinearLayout? = null
    private var btnPayWeChat: LinearLayout? = null
    private var weChatOrderBean: WeChatOrderResult? = null
    private var btnRefund: LinearLayout? = null
    private var evAppId: EditText? = null
    private var evCommodityName: EditText? = null
    private var evOrderAmout: EditText? = null
    private var mActivity: Activity? = null
    private var etWeChatServiceOrderAppId: EditText? = null
    private var etWeChatAppId: EditText? = null
    var mpay_url: String = ""
    var alipay_url: String = ""

    private val mHandler = Handler(Handler.Callback { msg ->
        var result: String
        when (msg.what) {
            respCreateAliPayOrderSucceed -> {
                result = msg.obj as String
                // 调起alipay收银台.........
                Logger.i("返回的内容----$result")
                try {
                    MacauPaySdk.aliPay(this@MainActivity, result, this@MainActivity)
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            }
            respCreateMPayOrderSucceed -> {
                result = msg.obj as String
                Logger.i("返回的内容----$result")
                try {
                    MacauPaySdk.macauPay(this@MainActivity, result, this@MainActivity)
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            }
        }
        false
    })

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mActivity = this
        initView()
    }

    private fun initView() {
        btnPayAli = findViewById(R.id.tb_trade_confirm_pay_ali)
        btnPayMacau = findViewById(R.id.tb_trade_confirm_pay_macau)
        btnPayWeChat = findViewById(R.id.tb_trade_confirm_pay_wechat)
        btnRefund = findViewById(R.id.btn_refund)
        btnRefund?.setOnClickListener(this)
        btnPayWeChat!!.setOnClickListener(this)
        btnPayAli!!.setOnClickListener(this)
        btnPayMacau!!.setOnClickListener(this)
        evAppId = findViewById(R.id.ev_app_id)
        evOrderAmout = findViewById(R.id.ev_order_amout)
        evCommodityName = findViewById(R.id.ev_app_name)
        etWeChatAppId = findViewById(R.id.ev_wechat_appid)
        etWeChatServiceOrderAppId = findViewById(R.id.ev_wechat_service_appid)
        // 在调起sdk时要设置sdk使用的环境,默认UAT环境 // 0 ：生产，1：sit，2 :UAT
        MacauPaySdk.setEnvironmentType(1)

        rbSit = findViewById(R.id.rb_sit)
        rbUat = findViewById(R.id.rb_uat)
        alipay_url = alipay_url_sit
        mpay_url = mpay_url_sit
        rbSit!!.isChecked = true
        rbSit!!.setOnClickListener(this)
        rbUat!!.setOnClickListener(this)
    }


    override fun onClick(v: View) {
        when (v.id) {
            R.id.tb_trade_confirm_pay_macau -> try {
                mPayAliPayOrderPayTest(mpay_url)
            } catch (e: Exception) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            }
            R.id.btn_refund -> try {
                doRefund()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            R.id.tb_trade_confirm_pay_ali -> try {
                mPayAliPayOrderPayTest(alipay_url)
            } catch (e: Exception) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            }

            R.id.tb_trade_confirm_pay_wechat -> try {
                weChatPayOrderTest(wechatpay_url)
            } catch (e: Exception) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            }
            R.id.rb_sit -> {
                mpay_url = mpay_url_sit
                alipay_url = alipay_url_sit
                MacauPaySdk.setEnvironmentType(1)
            }
            R.id.rb_uat -> {
                mpay_url = mpay_url_uat
                alipay_url = alipay_url_uat
                MacauPaySdk.setEnvironmentType(2)
            }
            else -> {
            }
        }
    }

    private fun doRefund() {
        val requestMap = JSONObject()
        requestMap.put("app_id", etWeChatServiceOrderAppId!!.text.toString())
        requestMap.put("api_name", "refund")
        requestMap.put("biz_api_code", "200020006")
        requestMap.put("data_type", "JSON")
        requestMap.put("charset", "utf-8")
        requestMap.put("timestamp", SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()))
        requestMap.put("sign_type", "RSA")
        requestMap.put("version", "1.0")
        val innerMsg = JSONObject()
        innerMsg.put("trade_no", weChatOrderBean!!.Data.trade_no)
        innerMsg.put("out_request_no", "")
        innerMsg.put("refund_amount", evOrderAmout!!.text.toString())
        innerMsg.put("refund_reason", "退款")
        innerMsg.put("operator_id", "Yx_001")
        innerMsg.put("store_id", "NJ_001")
        innerMsg.put("terminal_id", "NJ_T_001")
        requestMap.put("biz_content", innerMsg)
        val param = requestMap.toString()
        val body = RequestBody.create(JSON, param)
        val request = Request.Builder()
            .url(wechatpay_url)
            .post(body)
            .removeHeader("User-Agent")
            .addHeader("User-Agent", "macaupay")
            .addHeader("Content-Type", "application/json")
            .addHeader("accept", "*/*")
            .addHeader("connection", "Keep-Alive")
            .build()
        OkHttpClient().newCall(request).enqueue(object : Callback {
            val mHandler: Handler = Handler(mActivity!!.mainLooper)
            override fun onFailure(p0: Call, p1: IOException) {
                mHandler.post(Runnable {
                    kotlin.run {
                        Toast.makeText(mActivity, p1.message, Toast.LENGTH_SHORT).show()
                    }
                })

            }

            override fun onResponse(p0: Call, response: Response) {
                mHandler.post(Runnable {
                    kotlin.run {
                        if (response.code() == 200) {
                            val result = response.body()!!.string()
                            Logger.i("返回的内容----$result")
                            val resultObj = JSONObject(result)
                            Toast.makeText(mActivity, resultObj.getString("respMsg"), Toast.LENGTH_SHORT).show()
                        } else {
                            Toast.makeText(mActivity, response.message(), Toast.LENGTH_SHORT).show()
                        }
                    }
                })

            }
        })
    }
    val JSON = MediaType.parse("application/json; charset=utf-8")
    /**
     * wechatPay專用
     */
    @Throws(Exception::class)
    private fun weChatPayOrderTest(url: String) {
        MacauPaySdk.initWeChatData(etWeChatAppId!!.text.toString())
        val requestMap = JSONObject();
        requestMap.put("app_id", etWeChatServiceOrderAppId!!.text.toString())
        requestMap.put("api_name", "wxPreCreatePay")
        requestMap.put("biz_api_code", "100020014")
        requestMap.put("data_type", "JSON")
        requestMap.put("charset", "utf-8")
        requestMap.put("timestamp", SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()))
        requestMap.put("sign_type", "RSA")
        requestMap.put("version", "1.0")
        val innerMsg = JSONObject()
        innerMsg.put("out_trade_no", "")
        innerMsg.put("total_amount", evOrderAmout!!.text.toString())
        innerMsg.put("subject", evCommodityName!!.text.toString())
        innerMsg.put("trade_mode", "0002")
        innerMsg.put("body", "testdesc")
        innerMsg.put("currency", "MOP")
        innerMsg.put("operator_id", "Yx_001")
        innerMsg.put("store_id", "NJ_001")
        innerMsg.put("terminal_id", "NJ_T_001")
        innerMsg.put("submerchant_id", "NJ")
        innerMsg.put("trade_type", "APP")
        innerMsg.put("sub_app_id",etWeChatAppId!!.text.toString())
        innerMsg.put("sub_openid", "")
        innerMsg.put("notify_url", "")
        requestMap.put("biz_content", innerMsg)
        val param = requestMap.toString()
        val body = RequestBody.create(JSON, param)
        val request = Request.Builder()
            .url(url)
            .post(body)
            .removeHeader("User-Agent")
            .addHeader("User-Agent", "macaupay")
            .addHeader("Content-Type", "application/json")
            .addHeader("accept", "*/*")
            .addHeader("connection", "Keep-Alive")
            .build()
        OkHttpClient().newCall(request).enqueue(object : Callback {
            val mHandler = Handler(mActivity!!.mainLooper)
            override fun onFailure(call: Call, e: IOException) {
                Logger.d("返回的内容----" + e.message)
                mHandler.post(Runnable {
                    Toast.makeText(mActivity, "預下單失敗-網絡問題", Toast.LENGTH_SHORT).show()
                })

            }

            override fun onResponse(call: Call, response: Response) {
                mHandler.post(Runnable {
                    var result: String = ""
                    try {
                        result = response.body()!!.string()
                        Logger.i("返回的内容----$result")
                        weChatOrderBean = Gson().fromJson(result, WeChatOrderResult::class.javaObjectType)
                        if (checkApkExist(this@MainActivity, "com.tencent.mm")) {
                            btnRefund?.visibility = View.VISIBLE
                            MacauPaySdk.weChatPay(this@MainActivity, weChatOrderBean!!.Data.qr_code, this@MainActivity)
                        } else {
                            Toast.makeText(this@MainActivity, "未安裝微信", Toast.LENGTH_SHORT).show()
                        }

                    } catch (e: Exception) {
                        // TODO Auto-generated catch block
                        e.printStackTrace()
                        Toast.makeText(mActivity, "預下單失敗--" + result, Toast.LENGTH_SHORT).show()
                    }
                })


            }
        })
    }

    fun checkApkExist(ctx: Context, packageName: String?): Boolean {

        if (packageName == null || "" == packageName) {
            return false
        }
        try {
            val info = ctx.packageManager.getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES)
            return if (info != null) {
                true
            } else {
                false
            }
        } catch (e: PackageManager.NameNotFoundException) {
            return false
        }

    }

    /**
     * macau/alipay 支付
     *
     * @throws Exception
     */
    @Throws(Exception::class)
    private fun mPayAliPayOrderPayTest(url: String) {

        val formBody = FormBody.Builder()
            .add("app_id", evAppId!!.text.toString())
            .add("subject", evCommodityName!!.text.toString())
            .add("total_amount", evOrderAmout!!.text.toString()).build()
        val request = Request.Builder()
            .url(url)
            .post(formBody)
            .build()
        OkHttpClient().newCall(request).enqueue(object : Callback {
            val mMainHandler = Handler(mActivity!!.mainLooper)
            override fun onFailure(call: Call, e: IOException) {

                Logger.d("返回的内容----" + e.message)
                mMainHandler.post(Runnable {
                    Toast.makeText(mActivity, e.message, Toast.LENGTH_SHORT).show()
                })
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                try {
                    val result = response.body()!!.string()
                    val message = mHandler.obtainMessage()
                    when (url) {
                        alipay_url -> message.what = respCreateAliPayOrderSucceed
                        mpay_url -> message.what = respCreateMPayOrderSucceed
                    }
                    message.obj = result
                    mHandler.sendMessage(message)

                } catch (e: Exception) {
                    // TODO Auto-generated catch block
                    e.printStackTrace()
                }

            }
        })

    }

    // 使用支付寶支付后回調狀態碼
    // 9000 订单支付成功
    // 8000 正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态 .(支付宝服务端返回的错误码)
    // 4000 订单支付失败
    // 6001 用户中途取消
    // 6002 网络连接出错
    // 6004 支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态 。（支付宝客户端不能得到服务端的响应，往往是因为网络原因）
    // 1000 签名失败
    // 其它 其它支付错误
    override fun APayInterfaces(payResult: PayResult) {
        Logger.d("ResultStatus===" + payResult.resultStatus)
        Toast.makeText(this, "支付寶支付--" + payResult.result, Toast.LENGTH_LONG).show()
    }

    // 澳门通
    // 9000 :支付成功,6002: 网络连接出错,6001: 用户中途取消,4000
    // :订单支付失败，5000：支付异常,4004:无效订單,1000:簽名失敗,0001:手續費大於交易金額,4044:訂單金額無效

    override fun MPayInterfaces(payResult: PayResult) {
        Logger.d("ResultStatus===" + payResult.resultStatus)
        Toast.makeText(this, "MPay支付--" + payResult.result, Toast.LENGTH_LONG).show()
    }

    /**
     * 微信支付
     */
    override fun WeChatPayInterfaces(payResult: PayResult) {
        Logger.d("ResultStatus===" + payResult.resultStatus)
        Toast.makeText(this, "微信支付--" + payResult.resultStatus, Toast.LENGTH_LONG).show()
    }


}
